package com.auoem.radio.ui.channel;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;

import com.auctus.am.framework.utils.AmComUtils;
import com.auctus.am.framework.constants.AmConstants;
import com.auctus.am.framework.entity.ChannelInf;
import com.auctus.am.framework.imp.RadioManager;
import com.auctus.am.framework.interfaces.ComCallback;
import com.auctus.am.framework.picker.IIntPickDataWrap;
import com.auctus.am.framework.picker.RadioPickData;
import com.auctus.am.framework.tasks.RadioTaskManager;
import com.auctus.am.framework.tasks.SwitchChannelTask;
import com.auctus.am.framework.utils.LogM;
import com.auoem.radio.base.BaseActivity;
import com.auoem.radio.R;
import com.auoem.radio.common.custview.CustomTitlebar;
import com.auoem.radio.common.custview.EditDialogFragment;
import com.auoem.radio.common.custview.wheel.SimplePickerDialog;
import com.auoem.radio.common.utils.ResourceUtils;
import com.auoem.radio.common.utils.ToastUtils;
import com.auoem.radio.databinding.ActivityChannelInfBinding;

public class ChannelInfActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = "ChannelInfActivity";
    ActivityChannelInfBinding mBinding;

    ChannelInf channelInf;
    boolean isLastChDigital;

    EditDialogFragment mEditDialog;
    private SimplePickerDialog mSelectDialog;

    IIntPickDataWrap pickDataCt, pickDataColor, pickDataCtcType, pickDataCtcCode, pickDataCdcCode, pickDataChType;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = ActivityChannelInfBinding.inflate(getLayoutInflater());
        setContentView(mBinding.getRoot());
        initData();
        initActionBar();
        updateView();
    }

    private void initActionBar() {
        ActionBar actionBar = getSupportActionBar();
        assert actionBar != null;
        actionBar.hide();
        mBinding.ctChannel.setButtonOnClickCallback(new CustomTitlebar.ButtonCallback() {
            @Override
            public void OnClickResultCallback(CustomTitlebar.ButtonType btnType, View view) {
                switch (btnType) {
                    case LeftimgBtn:
                        finish();
                        break;
                }
            }
        });
        mBinding.ctChannel.setBackTxt(ResourceUtils.getResourcesString(R.string.hl_ch_inf_title, channelInf.channelId + 1));
    }

    private void initData() {
        Intent intent = getIntent();
        int chId = intent.getIntExtra(AmConstants.KEY_CHANNEL_ID, 0);
        channelInf = (ChannelInf) intent.getParcelableExtra(AmConstants.KEY_CHANNEL_OBJ);
        assert channelInf != null;
        isLastChDigital = channelInf.isDigModel;
        pickDataCt = RadioManager.getInstance().getRadioData().getCtPicker();
        pickDataColor = RadioPickData.getInstance().getChColorPick();
        pickDataCtcType = RadioPickData.getInstance().getChCtcType();

        pickDataCtcCode = RadioPickData.getInstance().getChctcCode();
        pickDataCdcCode = RadioPickData.getInstance().getChCdcCode();

        pickDataChType = RadioPickData.getInstance().getChType();
        LogM.d(TAG, channelInf.toString());
    }

    @Override
    public void onClick(View v) {
        if (v == mBinding.tvCtv) {
            selCt();
        } else if (v == mBinding.tvColorV) {
            selColor();
        } else if (v == mBinding.tvFreqTx) {
            editFreq(true);
        } else if (v == mBinding.tvFreqRx) {
            editFreq(false);
        } else if (v == mBinding.tvCtcTypeTx) {
            selCtcType(true);
        } else if (v == mBinding.tvCtcCodeTx) {
            selCtcCode(true);
        } else if (v == mBinding.tvCtcTypeRx) {
            selCtcType(false);
        } else if (v == mBinding.tvCtcCodeRx) {
            selCtcCode(false);
        } else if (v == mBinding.tvTypeV) {
            selChType();
        } else if (v == mBinding.btSave) {
            save();
        }
    }


    private void selCt() {
        showSingleSelect(pickDataCt, new SimplePickerDialog.OnPickListener() {
            @Override
            public void onPicked(int sel1, int v1) {
                channelInf.ctTag = v1;
                updateCt();
            }
        });
    }


    private void selColor() {
        showSingleSelect(pickDataColor, new SimplePickerDialog.OnPickListener() {
            @Override
            public void onPicked(int sel1, int v1) {
                channelInf.colorCode = v1;
                updateChBind();
            }
        });
    }

    private void editFreq(boolean isTx) {
        if (mEditDialog == null) {
            mEditDialog = new EditDialogFragment();
        }

        mEditDialog.setOnEditFinishListener(new EditDialogFragment.OnEditFinishListener() {
            @Override
            public void onFinished(String content) {
                try {
                    int iFreq = getEditFreq(content);
                    if (iFreq <= 0) {
                        ToastUtils.showShortToast(ChannelInfActivity.this, R.string.am_common_input_invalid);
                        return;
                    }
                    if (isTx) {
                        channelInf.freqTx = getEditFreq(content);
                    } else {
                        channelInf.freqRx = getEditFreq(content);
                    }
                    updateChBind();
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        });
//        mEditDialog.setInputType(InputType.TYPE_CLASS_TEXT);//todo 大部分使用普通字符
//        mEditDialog.setLines(lines);
        if (!mEditDialog.isAdded() && null == getSupportFragmentManager().findFragmentByTag("editDialog")) {
            mEditDialog.showNow(getSupportFragmentManager(), "editDialog");
        }
        mEditDialog.setContent(ResourceUtils.getResourcesString(R.string.hl_ch_inf_freq_hint), isTx ? channelInf.freqTx + "" : channelInf.freqRx + "");
        mEditDialog.setAttr(10, "");
    }

    private void selCtcType(boolean isTx) {
        showSingleSelect(pickDataCtcType, new SimplePickerDialog.OnPickListener() {
            @Override
            public void onPicked(int sel1, int v1) {
                if (isTx) {
                    channelInf.cdTypeTx = (short) v1;
                } else {
                    channelInf.cdTypeRx = (short) v1;
                }
                updateCdType(isTx, pickDataCtcType.getDisp(sel1), sel1 == 0);
                updateCdCodeOnType(isTx, v1);
            }
        });
    }


    private void selCtcCode(boolean isTx) {
        IIntPickDataWrap pickData = null;
        int type = isTx ? channelInf.cdTypeTx : channelInf.cdTypeRx;
        switch (type) {
            case ChannelInf.CD_TYPE_CTC:
                pickData = pickDataCtcCode;
                break;
            case ChannelInf.CD_TYPE_CDC:
                pickData = pickDataCdcCode;
                break;
        }
        if (pickData == null) return;//未选类型
//        IIntPickDataWrap finalPickData = pickData;
        showSingleSelect(pickData, new SimplePickerDialog.OnPickListener() {
            @Override
            public void onPicked(int sel1, int v1) {
                if (isTx) {
                    channelInf.cdCodeTx = (short) v1;
                    updateCtcTx();
                } else {
                    channelInf.cdCodeRx = (short) v1;
                    updateCtcRx();
                }
//                updateCdCode(isTx, finalPickData.getDisp(sel1));
            }
        });
    }

    private void selChType() {
        showSingleSelect(pickDataChType, new SimplePickerDialog.OnPickListener() {
            @Override
            public void onPicked(int sel1, int v1) {
                channelInf.isDigModel = sel1 == 1;
                boolean isValid = channelInf.validBeforeSwitchCh();
                if (!isValid) {
                    //todo return 没有联系人，需先配置联系人
                }
//                channelInf.ctTag = pickDataCt.getValue(0);
                channelInf.updateDataOnChType();
//                updateTypeView();
//                updateChBind();
                updateView();
            }
        });
    }


    public void showSingleSelect(IIntPickDataWrap intPickDataWrap, SimplePickerDialog.OnPickListener onPickListener) {
        if (mSelectDialog == null) {
            mSelectDialog = new SimplePickerDialog(this, intPickDataWrap, 0, onPickListener, null);
        } else {
            mSelectDialog.update(intPickDataWrap, SimplePickerDialog.INVALID, onPickListener, null);
        }
        mSelectDialog.show();
    }

    private void save() {
        RadioManager.getInstance().getRadioData().updateChannel(channelInf);
        if (RadioManager.getInstance().getRadioData().isCurChannel(channelInf.channelId) ) {
            setCurChange();
            return;
        }
        finish();
    }


    /*UPDATE*/

    private void updateView() {
        updateChBind();
        updateTypeView();
        updateCt();
        updateCtcTx();
        updateCtcRx();

    }

    private void updateTypeView() {
        mBinding.llAna.setVisibility(!channelInf.isDigModel ? View.VISIBLE : View.GONE);
        mBinding.llDig.setVisibility(channelInf.isDigModel ? View.VISIBLE : View.GONE);
    }

    private void updateChBind() {
        mBinding.setInf(channelInf);
    }

    private void updateCt() {
        String txt = pickDataCt != null ? pickDataCt.getDispOnValue(channelInf.ctTag) : "";
        mBinding.tvCtv.setText(txt);
    }

    private void updateCtcTx() {
        String txtTypeTx = pickDataCtcType.getDispOnValue(channelInf.cdTypeTx);
        mBinding.tvCtcTypeTx.setText(txtTypeTx);
        if (channelInf.cdTypeTx == 0) {
            mBinding.rlCodeTx.setVisibility(View.GONE);
            return;
        }
        mBinding.rlCodeTx.setVisibility(View.VISIBLE);
        IIntPickDataWrap pickData = null;
        switch (channelInf.cdTypeTx) {
            case ChannelInf.CD_TYPE_CTC:
                pickData = pickDataCtcCode;
                break;
            case ChannelInf.CD_TYPE_CDC:
                pickData = pickDataCdcCode;
                break;
        }
        if (pickData == null) {
            mBinding.tvCtcCodeTx.setText(R.string.hl_common_empty);
        } else {
            String txtCodeTx = pickData.getDispOnValue(channelInf.cdCodeTx);
            mBinding.tvCtcCodeTx.setText(TextUtils.isEmpty(txtCodeTx) ? "-" : txtCodeTx);
        }
    }

    private void updateCtcRx() {
        String txtTypeTx = pickDataCtcType.getDispOnValue(channelInf.cdTypeRx);
        mBinding.tvCtcTypeRx.setText(txtTypeTx);
        if (channelInf.cdTypeRx == 0) {
            mBinding.rlCodeRx.setVisibility(View.GONE);
            return;
        }
        mBinding.rlCodeRx.setVisibility(View.VISIBLE);
        IIntPickDataWrap pickData = null;
        switch (channelInf.cdTypeRx) {
            case ChannelInf.CD_TYPE_CTC:
                pickData = pickDataCtcCode;
                break;
            case ChannelInf.CD_TYPE_CDC:
                pickData = pickDataCdcCode;
                break;
        }
        if (pickData == null) {
            mBinding.tvCtcCodeRx.setText(R.string.hl_common_empty);
        } else {
            String txtCodeTx = pickData.getDispOnValue(channelInf.cdCodeRx);
            mBinding.tvCtcCodeRx.setText(TextUtils.isEmpty(txtCodeTx) ? "-" : txtCodeTx);
        }
    }

    private void updateCdCodeOnType(boolean isTx, int type) {
        String strCode = "-";
        if (isTx) {
            switch (type) {
                case 0:
                    channelInf.cdCodeTx = 0;
                    break;
                case 1:
                    channelInf.cdCodeTx = pickDataCtcCode.getValue(0);
                    strCode = pickDataCtcCode.getDisp(0);
                    break;
                case 2:
                    channelInf.cdCodeTx = pickDataCdcCode.getValue(0);
                    strCode = pickDataCdcCode.getDisp(0);
                    break;
            }
        } else {
            switch (type) {
                case 0:
                    channelInf.cdCodeRx = 0;
                    break;
                case 1:
                    channelInf.cdCodeRx = pickDataCtcCode.getValue(0);
                    strCode = pickDataCtcCode.getDisp(0);
                    break;
                case 2:
                    channelInf.cdCodeRx = pickDataCdcCode.getValue(0);
                    strCode = pickDataCdcCode.getDisp(0);
                    break;
            }
        }
        updateCdCode(isTx, strCode);
    }

    private void updateCdType(boolean isTx, String text, boolean isNo) {
        if (isTx) {
            mBinding.tvCtcTypeTx.setText(text);
            mBinding.rlCodeTx.setVisibility(isNo ? View.GONE : View.VISIBLE);
        } else {
            mBinding.tvCtcTypeRx.setText(text);
            mBinding.rlCodeRx.setVisibility(isNo ? View.GONE : View.VISIBLE);
        }
    }

    private void updateCdCode(boolean isTx, String text) {
        if (isTx) {
            mBinding.tvCtcCodeTx.setText(text);
        } else {
            mBinding.tvCtcCodeRx.setText(text);
        }
    }


    private int getEditFreq(String strFreq) {
        int lenFreq = strFreq.length();
        int dLenFreq = 9 - lenFreq;
        double mFreq = Math.pow(10, dLenFreq);
        double dFreq = Double.parseDouble(strFreq);
        int iFreq = (int) (dFreq * mFreq);
        int[] freqRange = AmComUtils.getFreqRange();
//        return iFreq < CpsConstants.MIN_FREQ || iFreq > CpsConstants.MAX_FREQ ? 0 : iFreq;
        return AmComUtils.maxMin(freqRange[0], freqRange[1], iFreq);
    }

    private void setCurChange() {
        showProgress(R.string.hl_ch_inf_update_progress_msg);
        RadioTaskManager.getInstance().startSwitchChannelTask(RadioManager.getInstance().getRadioData(), channelInf.channelId, new ComCallback<Boolean>() {
            @Override
            public void onCallback(Boolean isSucc, int code, String inf) {
                LogM.d(TAG, "setCurChange:  code: %d  msg: %s", code, inf);
                if (isSucc) {
                    toastResultUI(R.string.hl_ch_inf_update_succ);
                    finish();
                } else if (code == SwitchChannelTask.CODE_STOP) {
                    //主动停止，不处理
                } else if (code >= 2) {
                    toastResultUI(R.string.hl_ch_inf_update_part);
                } else {
                    toastResultUI(R.string.hl_ch_inf_update_failure);
                }
            }
        });
    }
}
